import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { invoke } from "@tauri-apps/api/core";
import { UserInterface } from "./UserInterface.tsx"
import { getCurrentWindow } from "@tauri-apps/api/window";
import { LogicalSize } from '@tauri-apps/api/dpi';
import { Timer } from "./Timer.tsx"
// import "./App.css";

function Register() {
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [username, setUsername] = useState("");
    const [ossAccessID, setOssAccessID] = useState("");
    const [ossKeySecret, setOssKeySecret] = useState("");
    const [ossReigion, setOssReigion] = useState("");
    const [bucketName, setBucketName] = useState("");
    const [message, setMessage] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const navigate = useNavigate();
    const { 
      mongoDBUrl, setMongoDBUrl,
    } = UserInterface();

    useEffect(()=> {
      getCurrentWindow().setSize(new LogicalSize(800, 900));
    }, [])

    const handleSubmit = async(e: { preventDefault: () => void; }) => {
      e.preventDefault();
      setIsLoading(true);
      setMessage("");
      // 检查密码是否匹配
      if (password !== confirmPassword) {
        setMessage("Passwords do not match");
        setIsLoading(false);
        return;
      }
      // 检查用户名和密码是否互相包含
      if (password.toLowerCase().includes(username.toLowerCase()) || 
          username.toLowerCase().includes(password.toLowerCase())) {
        setMessage("Username and password should not contain each other");
        setIsLoading(false);
        return;
      }
            // 检查密码复杂度
      const hasDigit = /[0-9]/.test(password);
      const hasLowerCase = /[a-z]/.test(password);
      const hasUpperCase = /[A-Z]/.test(password);
      if (!hasDigit){
        setMessage("Password must contain at least one digit");
        return;
      }else if(!hasLowerCase){
        setMessage("Password must contain at least one lowercase letter");
        return;
      } else if(!hasUpperCase) {
        setMessage("Password must contain at least one uppercase letter");
        return;
      }
      if(password.length < 6 || password.length > 13){
        setMessage("password must be at least 6 characters and password must be at most 12 characters");
        setIsLoading(false);
        return;
      }
      const ossAccessKey = {
        oss_access_id : ossAccessID,
        oss_key_secret : ossKeySecret,
        reigion : ossReigion,
        bucket : bucketName,
      }
      const user = {
        username : username,
        password : password,
      }
      console.log("oss_access", ossAccessKey);
      try {
        const response = await invoke<String>("register", {
          // invoke传参命名必须驼峰式
          ossAccess : ossAccessKey,
          user : user,
          mongodbUrl : mongoDBUrl 
        });
        
        console.log(response);
        setMessage(response as string);
         // 注册成功后清空输入字段
        if ((response as string).includes("successful")) {
          navigate("/");
        }
        setIsLoading(false);
      } catch (error) {
        console.error(error);
        setMessage(String(error));
      }
    };
  
    return (
      <main className="container">
        <h1 id="register-text">🙃Register</h1>
        <form onSubmit={handleSubmit}>
          <input
            id="input-username"
            onChange={(e) => setUsername(e.currentTarget.value)}
            type="text"
            placeholder="😇Enter username"
            value={username}
            required
          />
          <input 
            id="input-password" 
            onChange={(e) => setPassword(e.currentTarget.value)} 
            type="password" 
            placeholder="😊Enter password"
            value={password} 
            required
          />
          <input 
            id="input-confirm-password" 
            onChange={(e) => setConfirmPassword(e.currentTarget.value)} 
            type="password" 
            placeholder="😊Confirm password"
            value={confirmPassword} 
            required
          />
          <input
            id="input-oss-ak-id"
            onChange={(e) => setOssAccessID(e.currentTarget.value)}
            type="text"
            placeholder="😇Enter OSS access key ID"
            value={ossAccessID}
            required
          />
          <input
            id="input-oss-ak-password"
            onChange={(e) => setOssKeySecret(e.currentTarget.value)}
            type="password"
            placeholder="😇Enter OSS access key secret"
            value={ossKeySecret}
            required
          />
          <input
            id="input-oss-region"
            onChange={(e) => setOssReigion(e.currentTarget.value)}
            type="text"
            placeholder="😇Enter OSS region"
            value={ossReigion}
            required
          />
          <input
            id="input-oss-bucket-name"
            onChange={(e) => setBucketName(e.currentTarget.value)}
            type="text"
            placeholder="😇Enter OSS bucket name"
            value={bucketName}
            required
          />
          <input
            id="input-mongodb-url"
            onChange={(e) => setMongoDBUrl(e.currentTarget.value)}
            type="text"
            placeholder="😇Enter MongoDB URL"
            value={mongoDBUrl}
            required
          />
          <div className="button-container">
            <button type="submit" id="register-button">🫠Register</button>
            <button id="back-to-login" onClick={() => window.history.back()}>
              😁Back to Login
            </button>
          </div>
          <div className="infobar">
            {isLoading ? (
              <div id="login-loadingbar">
                <div id="login-loading">🔄loading...</div>
                <Timer />
              </div>
              ):( 
                  message && (
                  <div id={message.includes("successful")?
                  "success":"error"}>
                    {message}
                  </div>
                  )
                )
            }
          </div>
        </form>
      </main>
    )
  }
  
  export default Register;
